package com.google.code.bankagregator.core;

import com.google.code.bankagregator.core.entityServices.CreditService;
import com.google.code.bankagregator.core.entityServices.DepositService;
import com.google.code.bankagregator.entities.Credit;
import com.google.code.bankagregator.entities.Deposit;
import com.google.code.bankagregator.vo.AdapterResult;
import com.google.code.bankagregator.vo.AdapterWarning;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Instance for managing updates
 */
@Stateless
public class UpdateManager {

    /**
     * Email of warning recipient
     */
    public final String ADMIN_EMAIL = "kaiser666666@gmail.com";

    /**
     * Email subject with warning description
     */
    public final String WARNING_MESSAGE_SUBJECT = "Adapter Manager Warning";

    @EJB
    AdapterManager adapterManager;
    @EJB
    CreditService creditService;
    @EJB
    DepositService depositService;

    private final Logger log = Logger.getLogger(UpdateManager.class.getName());

    public void updateProducts() {
        List<AdapterResult> results = adapterManager.getAllResults();
        for (AdapterResult result : results) {
            //processing credits
            List<Credit> credits = result.getCredits();
            for (Credit credit : credits) {
                creditService.updateCredit(credit);
            }

            List<Deposit> deposits = result.getDeposits();
            for (Deposit deposit : deposits) {
                depositService.updateDeposit(deposit);
            }

            List<AdapterWarning> warnings = result.getWarnings();
            for (AdapterWarning warning : warnings) {
                notifyAdmin(warning);
            }
        }
    }

    private void notifyAdmin(AdapterWarning warning) {
        sendAdminEmail(warning.getWarning());
        log.log(Level.INFO, "Adapter Exception: " + warning.getWarning());
    }

    private void sendAdminEmail(String msg) {
//        Properties properties = new Properties();
//        Session session = Session.getDefaultInstance(properties, null);
//
//        Message message = new MimeMessage(session);
//        try {
//            message.setFrom(new InternetAddress(ADMIN_EMAIL));
//            message.addRecipient(Message.RecipientType.TO, new InternetAddress(ADMIN_EMAIL));
//            message.setSubject(WARNING_MESSAGE_SUBJECT);
//            message.setText(msg);
//            Transport.send(message);
//        } catch (MessagingException e) {
//            log.log(Level.WARNING, "sendAdminEmail Exception: " + e);
//        }

    }
}
